<template>
  <div class="app-container">
    <el-card class="page-container">
      <template #header>
        <div class="card-header">
          <h3>接口配置</h3>
          <el-button type="primary" @click="handleAddApi">
            <el-icon><Plus /></el-icon>
            新增接口
          </el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-container">
        <el-form :model="searchForm" inline>
          <el-form-item label="接口名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入接口名称"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="关联表">
            <el-select
              v-model="searchForm.tableId"
              placeholder="请选择关联表"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="table in tables"
                :key="table.id"
                :label="`${table.name} (${table.comment})`"
                :value="table.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="HTTP方法">
            <el-select
              v-model="searchForm.method"
              placeholder="请选择HTTP方法"
              clearable
              style="width: 120px"
            >
              <el-option label="GET" value="GET" />
              <el-option label="POST" value="POST" />
              <el-option label="PUT" value="PUT" />
              <el-option label="DELETE" value="DELETE" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 接口列表 -->
      <el-table
        :data="filteredApiEndpoints"
        stripe
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="name" label="接口名称" min-width="200" />

        <el-table-column label="HTTP方法" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getMethodColor(row.method)">
              {{ row.method }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="path" label="接口路径" min-width="200">
          <template #default="{ row }">
            <el-text type="primary" class="api-path">
              {{ row.path }}
            </el-text>
          </template>
        </el-table-column>

        <el-table-column label="关联表" width="150">
          <template #default="{ row }">
            <el-tag type="info">
              {{ row.tableName }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="查询字段" width="120" align="center">
          <template #default="{ row }">
            <div class="count-display">
              <el-icon class="count-icon" color="#409eff">
                <Search />
              </el-icon>
              <span class="count-number">{{ row.queryFields?.filter(f => f.enabled)?.length || 0 }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="返回字段" width="120" align="center">
          <template #default="{ row }">
            <div class="count-display">
              <el-icon class="count-icon" color="#67c23a">
                <View />
              </el-icon>
              <span class="count-number">{{ row.responseFields?.filter(f => f.enabled)?.length || 0 }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="分页" width="80" align="center">
          <template #default="{ row }">
            <el-icon :color="row.enablePagination ? '#67C23A' : '#C0C4CC'">
              <Check v-if="row.enablePagination" />
              <Close v-else />
            </el-icon>
          </template>
        </el-table-column>

        <el-table-column label="排序" width="80" align="center">
          <template #default="{ row }">
            <el-icon :color="row.enableSort ? '#67C23A' : '#C0C4CC'">
              <Check v-if="row.enableSort" />
              <Close v-else />
            </el-icon>
          </template>
        </el-table-column>

        <el-table-column prop="description" label="接口描述" min-width="200" show-overflow-tooltip />

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleConfigApi(row)"
            >
              <el-icon><Setting /></el-icon>
              配置
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="handleEditApi(row)"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteApi(row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 接口基本信息对话框 -->
    <el-dialog
      v-model="apiDialogVisible"
      :title="apiDialogTitle"
      width="600px"
      :close-on-click-modal="false"
      class="api-dialog"
    >
      <el-form
        ref="apiFormRef"
        :model="apiForm"
        :rules="apiFormRules"
        label-width="100px"
      >
        <el-form-item label="接口名称" prop="name">
          <el-input
            v-model="apiForm.name"
            placeholder="请输入接口名称"
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="HTTP方法" prop="method">
              <el-select v-model="apiForm.method" placeholder="请选择" style="width: 100%">
                <el-option label="GET" value="GET" />
                <el-option label="POST" value="POST" />
                <el-option label="PUT" value="PUT" />
                <el-option label="DELETE" value="DELETE" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="接口路径" prop="path">
              <el-input
                v-model="apiForm.path"
                placeholder="/api/users"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="关联表" prop="tableId">
          <el-select
            v-model="apiForm.tableId"
            placeholder="请选择关联表"
            style="width: 100%"
            @change="handleTableChange"
          >
            <el-option
              v-for="table in tables"
              :key="table.id"
              :label="`${table.name} (${table.comment})`"
              :value="table.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="接口描述">
          <el-input
            v-model="apiForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入接口描述"
          />
        </el-form-item>

        <el-form-item label="功能选项">
          <el-checkbox v-model="apiForm.enablePagination">
            启用分页
          </el-checkbox>
          <el-checkbox v-model="apiForm.enableSort">
            启用排序
          </el-checkbox>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="apiDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="handleSubmitApi">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 接口详细配置对话框 -->
    <el-dialog
      v-model="configDialogVisible"
      title="接口详细配置"
      width="80%"
      :close-on-click-modal="false"
      class="config-dialog"
    >
      <el-tabs v-model="activeTab" type="card">
        <!-- 查询字段配置 -->
        <el-tab-pane label="查询字段" name="query">
          <div class="tab-content">
            <div class="tab-header">
              <h4>配置查询参数</h4>
              <el-button type="primary" size="small" @click="handleAddQueryField">
                <el-icon><Plus /></el-icon>
                添加查询字段
              </el-button>
            </div>

            <el-table :data="currentApiConfig?.queryFields || []" border stripe>
              <el-table-column label="启用" width="80" align="center">
                <template #default="{ row }">
                  <el-switch v-model="row.enabled" />
                </template>
              </el-table-column>
              <el-table-column prop="fieldName" label="字段名" width="150" />
              <el-table-column prop="tableName" label="所属表" width="120" />
              <el-table-column label="查询操作符" width="120">
                <template #default="{ row }">
                  <el-select v-model="row.operator" size="small" style="width: 100%">
                    <el-option label="等于" value="eq" />
                    <el-option label="不等于" value="ne" />
                    <el-option label="大于" value="gt" />
                    <el-option label="大于等于" value="gte" />
                    <el-option label="小于" value="lt" />
                    <el-option label="小于等于" value="lte" />
                    <el-option label="模糊匹配" value="like" />
                    <el-option label="包含" value="in" />
                    <el-option label="范围" value="between" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="必填" width="80" align="center">
                <template #default="{ row }">
                  <el-switch v-model="row.required" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #default="{ row, $index }">
                  <el-button
                    type="danger"
                    size="small"
                    @click="handleRemoveQueryField($index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 返回字段配置 -->
        <el-tab-pane label="返回字段" name="response">
          <div class="tab-content">
            <div class="tab-header">
              <h4>配置返回字段</h4>
              <el-button type="primary" size="small" @click="handleAddResponseField">
                <el-icon><Plus /></el-icon>
                添加返回字段
              </el-button>
            </div>

            <el-table :data="currentApiConfig?.responseFields || []" border stripe>
              <el-table-column label="启用" width="80" align="center">
                <template #default="{ row }">
                  <el-switch v-model="row.enabled" />
                </template>
              </el-table-column>
              <el-table-column prop="fieldName" label="字段名" width="150" />
              <el-table-column prop="tableName" label="所属表" width="120" />
              <el-table-column label="字段别名" width="150">
                <template #default="{ row }">
                  <el-input v-model="row.alias" size="small" placeholder="可选" />
                </template>
              </el-table-column>
              <el-table-column prop="relationPath" label="关联路径" min-width="200">
                <template #default="{ row }">
                  <el-tag
                    v-for="(path, index) in row.relationPath"
                    :key="index"
                    size="small"
                    style="margin-right: 5px;"
                  >
                    {{ path }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #default="{ row, $index }">
                  <el-button
                    type="danger"
                    size="small"
                    @click="handleRemoveResponseField($index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <el-button @click="configDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="handleSaveApiConfig">
          保存配置
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import type { ApiEndpoint, DataTable, QueryFieldConfig, ResponseFieldConfig } from "../types"
import {
  Check,
  Close,
  Delete,
  Edit,
  Plus,
  Refresh,
  Search,
  Setting,
  View
} from "@element-plus/icons-vue"
import { ElMessage, ElMessageBox } from "element-plus"
import { computed, onMounted, reactive, ref } from "vue"
import { databaseApi, endpointsApi } from "@/common/apis"

// 响应式数据
const loading = ref(false)
const tables = ref<DataTable[]>([])
const apiEndpoints = ref<ApiEndpoint[]>([])
const apiDialogVisible = ref(false)
const configDialogVisible = ref(false)
const isEditApi = ref(false)
const currentApiConfig = ref<ApiEndpoint>()
const activeTab = ref("query")

// 搜索表单
const searchForm = reactive({
  name: "",
  tableId: "",
  method: ""
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 接口表单
const apiForm = reactive({
  id: "",
  name: "",
  path: "",
  method: "GET" as any,
  tableId: "",
  tableName: "",
  description: "",
  enablePagination: true,
  enableSort: true
})

// 表单验证规则
const apiFormRules = {
  name: [
    { required: true, message: "请输入接口名称", trigger: "blur" }
  ],
  method: [
    { required: true, message: "请选择HTTP方法", trigger: "change" }
  ],
  path: [
    { required: true, message: "请输入接口路径", trigger: "blur" },
    { pattern: /^\//, message: "接口路径必须以 / 开头", trigger: "blur" }
  ],
  tableId: [
    { required: true, message: "请选择关联表", trigger: "change" }
  ]
}

// 表单引用
const apiFormRef = ref()

// 计算属性
const apiDialogTitle = computed(() => isEditApi.value ? "编辑接口" : "新增接口")

const filteredApiEndpoints = computed(() => {
  let result = apiEndpoints.value

  if (searchForm.name) {
    result = result.filter(api =>
      api.name.toLowerCase().includes(searchForm.name.toLowerCase())
      || api.path.toLowerCase().includes(searchForm.name.toLowerCase())
    )
  }

  if (searchForm.tableId) {
    result = result.filter(api => api.tableId === searchForm.tableId)
  }

  if (searchForm.method) {
    result = result.filter(api => api.method === searchForm.method)
  }

  pagination.total = result.length
  const start = (pagination.currentPage - 1) * pagination.pageSize
  return result.slice(start, start + pagination.pageSize)
})

// 方法
async function loadData() {
  loading.value = true
  try {
    // 并行加载数据表和接口数据
    const [tablesResponse, endpointsResponse] = await Promise.all([
      databaseApi.getImportedTables({ current: 1, size: 1000 }), // 加载所有表用于下拉选择
      endpointsApi.getEndpoints({
        current: pagination.current,
        size: pagination.size,
        name: searchForm.name,
        tableId: searchForm.tableId,
        method: searchForm.method
      })
    ])

    // 转换数据表格式
    tables.value = tablesResponse.data.records.map((dbTable: any) => ({
      id: dbTable.tableId?.toString() || dbTable.id?.toString() || "",
      name: dbTable.tableName || dbTable.name || "",
      comment: dbTable.tableComment || dbTable.comment || "",
      fields: dbTable.fields || [],
      createdAt: dbTable.createTime || dbTable.createdAt || "",
      updatedAt: dbTable.updateTime || dbTable.updatedAt || ""
    })) as DataTable[]

    // 转换API接口格式
    apiEndpoints.value = endpointsResponse.data.records.map((endpoint: any) => ({
      id: endpoint.endpointId?.toString() || endpoint.id?.toString() || "",
      name: endpoint.endpointName || endpoint.name || "",
      path: endpoint.endpointPath || endpoint.path || "",
      method: endpoint.httpMethod || endpoint.method || "GET",
      tableId: endpoint.tableId?.toString() || "",
      tableName: endpoint.tableName || "",
      queryFields: endpoint.requestParameters || endpoint.queryFields || [],
      responseFields: endpoint.responseFields || [],
      description: endpoint.description || "",
      enablePagination: endpoint.enablePagination || false,
      enableSort: endpoint.enableSorting || endpoint.enableSort || false
    })) as ApiEndpoint[]

    pagination.total = endpointsResponse.data.total
    pagination.current = endpointsResponse.data.current
    pagination.pages = endpointsResponse.data.pages
  } catch (error) {
    console.error("加载数据失败:", error)
    ElMessage.error("加载数据失败，请稍后重试")
    tables.value = []
    apiEndpoints.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

function getMethodColor(method: string): string {
  const colorMap: Record<string, string> = {
    GET: "success",
    POST: "primary",
    PUT: "warning",
    DELETE: "danger"
  }
  return colorMap[method] || "info"
}

function handleSearch() {
  pagination.currentPage = 1
}

function handleReset() {
  searchForm.name = ""
  searchForm.tableId = ""
  searchForm.method = ""
  pagination.currentPage = 1
}

function handleSizeChange(size: number) {
  pagination.pageSize = size
  pagination.currentPage = 1
}

function handleCurrentChange(page: number) {
  pagination.currentPage = page
}

function handleAddApi() {
  isEditApi.value = false
  apiDialogVisible.value = true
  resetApiForm()
}

function handleEditApi(api: ApiEndpoint) {
  isEditApi.value = true
  apiDialogVisible.value = true

  apiForm.id = api.id
  apiForm.name = api.name
  apiForm.path = api.path
  apiForm.method = api.method
  apiForm.tableId = api.tableId
  apiForm.tableName = api.tableName
  apiForm.description = api.description || ""
  apiForm.enablePagination = api.enablePagination
  apiForm.enableSort = api.enableSort
}

async function handleDeleteApi(api: ApiEndpoint) {
  try {
    await ElMessageBox.confirm(
      `确定要删除接口 "${api.name}" 吗？删除后不可恢复。`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    )

    const index = apiEndpoints.value.findIndex(a => a.id === api.id)
    if (index > -1) {
      apiEndpoints.value.splice(index, 1)
      ElMessage.success("删除成功")
    }
  } catch {
    ElMessage.info("已取消删除")
  }
}

function handleConfigApi(api: ApiEndpoint) {
  currentApiConfig.value = api
  configDialogVisible.value = true
  activeTab.value = "query"
}

function handleTableChange(tableId: string) {
  const table = tables.value.find(t => t.id === tableId)
  if (table) {
    apiForm.tableName = table.name
  }
}

async function handleSubmitApi() {
  try {
    await apiFormRef.value?.validate()

    if (isEditApi.value) {
      // 编辑接口
      const index = apiEndpoints.value.findIndex(a => a.id === apiForm.id)
      if (index > -1) {
        Object.assign(apiEndpoints.value[index], {
          name: apiForm.name,
          path: apiForm.path,
          method: apiForm.method,
          tableId: apiForm.tableId,
          tableName: apiForm.tableName,
          description: apiForm.description,
          enablePagination: apiForm.enablePagination,
          enableSort: apiForm.enableSort
        })
        ElMessage.success("编辑成功")
      }
    } else {
      // 新增接口
      const newApi: ApiEndpoint = {
        id: `${apiForm.tableId}-${Date.now()}`,
        name: apiForm.name,
        path: apiForm.path,
        method: apiForm.method,
        tableId: apiForm.tableId,
        tableName: apiForm.tableName,
        description: apiForm.description,
        enablePagination: apiForm.enablePagination,
        enableSort: apiForm.enableSort,
        queryFields: [],
        responseFields: []
      }
      apiEndpoints.value.unshift(newApi)
      ElMessage.success("新增成功")
    }

    apiDialogVisible.value = false
    resetApiForm()
  } catch (error) {
    console.error("接口表单验证失败:", error)
  }
}

function handleAddQueryField() {
  if (!currentApiConfig.value) return

  const mainTable = tables.value.find(t => t.id === currentApiConfig.value!.tableId)
  if (!mainTable || mainTable.fields.length === 0) {
    ElMessage.warning("请先配置主表字段")
    return
  }

  const newQueryField: QueryFieldConfig = {
    fieldId: mainTable.fields[0].id,
    fieldName: mainTable.fields[0].name,
    tableId: mainTable.id,
    tableName: mainTable.name,
    operator: "eq",
    required: false,
    enabled: true
  }

  currentApiConfig.value.queryFields.push(newQueryField)
}

function handleRemoveQueryField(index: number) {
  if (currentApiConfig.value) {
    currentApiConfig.value.queryFields.splice(index, 1)
  }
}

function handleAddResponseField() {
  if (!currentApiConfig.value) return

  const mainTable = tables.value.find(t => t.id === currentApiConfig.value!.tableId)
  if (!mainTable || mainTable.fields.length === 0) {
    ElMessage.warning("请先配置主表字段")
    return
  }

  const newResponseField: ResponseFieldConfig = {
    fieldId: mainTable.fields[0].id,
    fieldName: mainTable.fields[0].name,
    tableId: mainTable.id,
    tableName: mainTable.name,
    enabled: true
  }

  currentApiConfig.value.responseFields.push(newResponseField)
}

function handleRemoveResponseField(index: number) {
  if (currentApiConfig.value) {
    currentApiConfig.value.responseFields.splice(index, 1)
  }
}

function handleSaveApiConfig() {
  ElMessage.success("接口配置保存成功")
  configDialogVisible.value = false
}

function resetApiForm() {
  apiForm.id = ""
  apiForm.name = ""
  apiForm.path = ""
  apiForm.method = "GET"
  apiForm.tableId = ""
  apiForm.tableName = ""
  apiForm.description = ""
  apiForm.enablePagination = true
  apiForm.enableSort = true
  apiFormRef.value?.clearValidate()
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.page-container {
  min-height: calc(100vh - 120px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #303133;
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.api-path {
  font-family: "Courier New", monospace;
  font-weight: 500;
}

:deep(.config-dialog) .tab-content {
  min-height: 400px;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.tab-header h4 {
  margin: 0;
  color: #303133;
}

:deep(.config-dialog .el-dialog__body) {
  padding: 10px 20px;
}

:deep(.el-tabs__content) {
  padding: 20px 0;
}

.count-display {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 4px 8px;
  background-color: #f8f9fa;
  border-radius: 16px;
  border: 1px solid #e4e7ed;
}

.count-icon {
  font-size: 16px;
}

.count-number {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  min-width: 20px;
  text-align: center;
}

/* 弹出框样式隔离 */
:deep(.api-dialog .el-dialog__body) {
  padding: 20px;
}

:deep(.api-dialog .el-form-item__label) {
  font-weight: 500;
  color: #303133;
}
</style>
